package com.shenglaotuan.community.common.utils;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * 处理文件的工具类
 */
public class FileUtils {


    /**
     * 剪切文件
     * @param srcPath 原文件路径
     * @param destPath 目标文件路径
     */
    public static void MVFile(String srcPath, String destPath){
        File src = new File(srcPath);
        File dest = new File(destPath);

        // 判断parent目录是否不存在
        if (!dest.getParentFile().exists()) {
            // 是：创建目录
            dest.getParentFile().mkdirs();
        }

        try (
                FileInputStream in = new FileInputStream(src);
                FileOutputStream out = new FileOutputStream(dest);
        ){
            byte[] data = new byte[1024 * 8];
            int len = -1;
            while((len = in.read(data)) != -1){
                out.write(data, 0, len);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        src.delete();
    }

    /**
     * 设置下载参数
     * @param response 响应对象
     * @param name 文件名
     */
    public static void setDownload(HttpServletResponse response, String name) throws UnsupportedEncodingException {
        response.reset();
        response.setContentType("application/octet-stream; charset=utf-8");
        response.setHeader("Content-Disposition", "attachment; filename="+ URLEncoder.encode(name, "UTF-8"));
    }

}
